import axios from 'axios'
import config from '../utils/config'
import { Message } from 'element-ui'
import { getTokenInfo } from '../utils/publicFun'

// 引入错误提示码
import codeList from './HttpStatusCode'

// 设置登录（获取token）的API
const loginUrl = '/pclogin'

// 创建axios实例
const baseUrl = config.BASE_URL
const requestTimeout = config.REQUEST_TIMEOUT
let ifNeedLogin = false
const service = axios.create({
  baseURL: baseUrl,
  timeout: requestTimeout // 请求超时时间
})
const serviIntercept = () => {
  if (!config.SERVICE_INTERCEPT) return
  // 请求拦截拦截器
  service.interceptors.request.use(
    config => {
      config.headers.userName = (() => {
        if (localStorage.userInfo) {
          return encodeURIComponent(JSON.parse(localStorage.userInfo).userName)
        } else {
          return ''
        }
      })()
      config.headers.userCode = (() => {
        if (localStorage.userInfo) {
          return JSON.parse(localStorage.userInfo).userCode
        } else {
          return ''
        }
      })()
      // config.headers.roleName = (() => {
      //   if (localStorage.userInfo) {
      //     return JSON.parse(localStorage.userInfo).roleName
      //   } else {
      //     return ''
      //   }
      // })()
      config.headers.userId = (() => {
        if (localStorage.userInfo) {
          return JSON.parse(localStorage.userInfo).userId
        } else {
          return ''
        }
      })()
      if (config.url !== loginUrl) {
        config.headers.Authorization = (() => {
          if (getTokenInfo()) {
            return getTokenInfo()
          } else {
            localStorage.removeItem('userInfo')
          }
        })()
      }
      return config
    },
    error => {
      console.log(error)
      Promise.reject(error)
    }
  )
  // 响应拦截
  service.interceptors.response.use(
    res => {
      if (res.data.code === 401) {
        if (!ifNeedLogin) {
          ifNeedLogin = true
          Message.warning(res.data?.message || '登录过期，请重新登录')
        }
        setTimeout(() => {
          localStorage.clear()
          sessionStorage.clear()
          location.href = '/login'
        }, 500)
      } else {
        return res.data
      }
    },
    // 请求失败情况
    error => {
      const { response } = error
      if (response) {
        // 若状态码 非 2XX 或 1XX 判断为网络异常 从网络异常表中寻找错误提示
        if (response.status >= 300) {
          const currentError = codeList.find(k => k.code === response.status)
          Message.error(currentError && currentError.tips ? currentError.tips : '服务故障，请检查！')
          // localStorage.userInfo = ''
          // localStorage.tokenInfo = ''
          // location.href = '/login'
        }
        return Promise.reject(response)
      } else {
        if (error.message) {
          console.log(error.message)
        } else {
          console.log('服务故障，请检查！')
        }
        return Promise.resolve()
      }
    })
}
// 响应拦截方法
serviIntercept()
export default service
